require 'open-uri'

class OpmlController < ApplicationController
    layout "default"

    def upload_opml_file

        @page_title = 'OPML Results'

        if !request.post?
            redirect_to(manage_aggregations_path)
        end

        opml = nil
        
        if params[:uri]
            opml = fetch(params[:uri])
            opml = REXML::Document.new(opml) unless opml.nil?
        elsif params[:opml][:uri]
            opml = fetch(params[:opml][:uri])
            opml = REXML::Document.new(opml) unless opml.nil?
        else
            opml_field = params[:opml][:uploaded_opml]
            opml_data = opml_field.read
            opml = REXML::Document.new(opml_data) unless opml_data.nil?
        end

        @aggregation = Aggregation.find(params[:aggregation_id])
        @opml = Opml.new
        @opml.setup_feeds(opml, @aggregation) unless opml.nil?

        if !@opml.found_feeds?
            flash[:message] = 'Unable to find any feeds in the OPML file.  Please ensure this is a valid file and try again.'
        end

        respond_to do |format|
            format.html
        end

    end    
    
    def add_opml_file

        @opml = Opml.new
        @opml.setup_feeds(opml)
        if !@opml.found_feeds?
            flash[:message] = 'Unable to find any feeds in the OPML file.  Please ensure this is a valid file and try again.'
        end

        respond_to do |format|
            format.html
        end

    end

    protected
    def fetch(uri)
        open(uri) do |f|
            f.read
        end
    end 

end
